﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using myu.Data;

namespace Sar
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(String[] argv)
        {
            if (argv.Length != 0)
            {
                executeCommand();
                return;
            }
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                FormLogin loginForm = new FormLogin();
                Application.Run(loginForm);
                if (loginForm.DialogResult == DialogResult.OK)
                {
                    loginForm.Dispose();
                    Application.Run(new FormMain(loginForm.textBoxUsername.Text, loginForm.Previlege));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n"
                    + ex.Source + "\n"
                    + ex.StackTrace + "\n"
                    + ex.TargetSite.ToString() + "\n");
                throw;
            }

        }

        static void executeCommand()
        {
            DataTable table = SqlDataOpr.fetchData("SELECT * FROM Sar.dbo.Command ORDER BY CommandNO");
            foreach (String arg in Environment.GetCommandLineArgs())
            {
                for (int i = 0; i < table.Rows.Count; i++)
                    if (table.Rows[i]["CommandName"].ToString() == arg)
                        try
                        {
                            Process process = new Process();
                            process.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                            process.StartInfo.Arguments = "/c \"" + table.Rows[i]["CommandLine"].ToString() + "\"";
                            process.StartInfo.UseShellExecute = false;
                            process.StartInfo.CreateNoWindow = true;
                            //process.StartInfo.WorkingDirectory = table.Rows[i]["WorkDirectory"].ToString();
                            process.Start();
                            //process.WaitForInputIdle();
                        }
                        catch (InvalidOperationException ex)
                        {
                            MessageBox.Show(ex.Message + "\n"
                                + ex.Source + "\n"
                                + ex.StackTrace + "\n"
                                + ex.TargetSite.ToString() + "\n");
                        }
            }
            return;
        }
    }
}
